package ro.gateway.aida.usr;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Hashtable;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ro.gateway.aida.db.PersistenceManager;
import ro.gateway.aida.db.PersistenceToken;
import ro.gateway.aida.obj.Country;
import ro.gateway.aida.obj.db.AIDALocationDB;
import ro.gateway.aida.srv.EditorServlet;
import ro.gateway.aida.usr.messaging.LPDRelay;
import ro.gateway.aida.utils.HttpUtils;
import ro.gateway.aida.utils.SysProp;
import ro.gateway.aida.utils.Utils;
import ro.xblue.translator.Module_DB;
import ro.xblue.translator.TranslatorConstants;
import ro.xblue.translator.Translator_DB;



/**
 * <p>Title: Romanian AIDA</p>
 * <p>Description: :D application</p>
 * <p>Copyright: Copyright (comparator) 2003</p>
 * <p>Company: Romania Development Gateway </p>
 * @author Mihai Popoaei, mihai_popoaei@yahoo.com, smike@intellisource.ro
 * @version 1.0-* @version $Id: EditUserServlet.java,v 1.1 2004/10/24 23:37:05 mihaipostelnicu Exp $
 */
public class EditUserServlet extends EditorServlet
{
      public String getJSP_PAGE()
      {
            return JSP_PAGE;
      }

      public String getPNAME_BEANS()
      {
            return PNAME_BEANS;
      }

      protected void edit(
            HttpServletRequest request,
            HttpServletResponse response )
            throws IOException, ServletException
      {
            ;
            request.setAttribute( PNAME_SCREEN, PV_SCR_EDIT );
            request.getRequestDispatcher( JSP_PAGE ).
                  forward( request, response );
      }

      protected void other_action_performed(
            HttpServletRequest request,
            HttpServletResponse response,
            String action )
            throws IOException, ServletException
      {
      }

      protected void confirm(
            HttpServletRequest request,
            HttpServletResponse response )
            throws IOException, ServletException
      {
            ServletContext application = this.getServletContext();
            PersistenceToken token = PersistenceManager.tokenLookup( application );
            UserDB pers_man = UserDB.getManager( token );

            Hashtable bean = ( Hashtable ) request.getAttribute( PNAME_BEAN );
            User item = ( User ) bean.get( PNAME_USER );

            item.setFirstNames( HttpUtils.getValidTrimedString( request, "firstnames", null ) );
            item.setLastName( HttpUtils.getValidTrimedString( request, "lastname", null ) );
            item.setEmail( HttpUtils.getValidTrimedString( request, "email", null ) );
            if ( item.getEmail() != null ) item.setEmail( item.getEmail().toLowerCase() );
            item.setLogin( HttpUtils.getValidTrimedString( request, "login", null ) );
            if ( item.getLogin() != null ) item.setLogin( item.getLogin().toLowerCase() );
            item.setWorkingLanguage( HttpUtils.getValidTrimedString( request, "wlang", null ) );
            item.setStandby( HttpUtils.getInt( request, "standby", 0 ) == 1 );
            item.setOrganization( HttpUtils.getValidTrimedString( request, "organization", null ) );
            String pass = HttpUtils.getValidTrimedString( request, "pass", null );
            String repass = HttpUtils.getValidTrimedString( request, "repass", null );
            item.setCountry_iso3( HttpUtils.getValidTrimedString( request, "ucountry", null ) );


            ArrayList errors = new ArrayList();
            if ( item.getLogin() != null && item.getId() == -1 )
            {
                  try
                  {
                        User x = pers_man.getByLogin( item.getLogin() );
                        if ( x != null )
                        {
                              errors.add( "err.userexists" );
                        }
                  }
                  catch ( SQLException sqlex )
                  {
                        sqlex.printStackTrace();
                  }
            }
            if ( pass != null )
            {
                  if ( pass.equals( repass ) )
                  {
                        item.setPass( HttpUtils.getHash( pass ) );
                        item.setClear_password( pass );
                  }
                  else
                  {
                        errors.add( "err.passnm" );
                  }
            }
            else if ( item.getPass() == null )
            {
                  errors.add( "err.passreq" );
            }

            if ( item.getEmail() == null )
            {
                  errors.add( "err.empty.email" );
            }
            if ( item.getLogin() == null )
            {
                  errors.add( "err.empty.login" );
            }

            String[] arr_errors = null;
            if ( errors.size() > 0 )
            {
                  arr_errors = new String[ errors.size() ];
                  errors.toArray( arr_errors );
            }

            if ( errors.size() > 0 )
            {
                  request.setAttribute( PNAME_ERRORS, arr_errors );
                  request.setAttribute( PNAME_SCREEN, PV_SCR_EDIT );
                  request.getRequestDispatcher( JSP_PAGE ).
                        forward( request, response );
                  return;
            }

            request.setAttribute( PNAME_SCREEN, PV_SCR_CONFIRM );
            request.getRequestDispatcher( JSP_PAGE ).
                  forward( request, response );
      }

      protected void start_editing(
            ServletContext application,
            HttpServletRequest request,
            HttpServletResponse response )
            throws IOException, ServletException
      {
            super.start_editing( application, request, response );
            PersistenceToken token = PersistenceManager.
                  tokenLookup( this.getServletContext() );
            HttpSession session = request.getSession();
            Hashtable beans = ( Hashtable ) session.getAttribute( PNAME_BEANS );
            Hashtable bean = ( Hashtable ) request.getAttribute( PNAME_BEAN );

            // rescriu action... vreau sa fie default register, nu new
            String action = HttpUtils.getValidTrimedString(
                  request, "action", PV_ACTION_REGISTER );
            bean.put( PNAME_ACTION, action );
            if ( PV_ACTION_REGISTER.equals( action ) )
            {
                  bean.put( "REGISTERING", "true" );
            }
            String key = ( String ) request.getAttribute( PNAME_KEY );

            if ( PV_ACTION_EDIT.equals( action ) || PV_ACTION_DELETE.equals( action ) )
            {
                  long id = HttpUtils.getLong( request, "id", -1 );
                  User user = null;
                  try
                  {
                        user = UserDB.getManager( token ).getById( id );
                  }
                  catch ( SQLException e )
                  {
                        e.printStackTrace();
                  }

                  if ( user == null )
                  {
                        user = new User();
                        user.setWorkingLanguage( Utils.getProperty( token, "defaultLang" ) );
                        bean.put( PNAME_USER, user );
                        request.setAttribute( PNAME_SCREEN, PV_SCR_ERROR );
                        request.setAttribute( PNAME_ERRORS, new String[]{"User not found"} );
                        request.getRequestDispatcher( JSP_PAGE ).
                              forward( request, response );
                        return;
                  }

                  Arbiter ar = Arbiter.getManager( token );
                  User logged_user = UserUtils.getLogged( request, response );
                  boolean has_rights =
                        ( logged_user != null ) &&
                        ( ( logged_user.getId() == user.getId() )
                        || ( ar.canDo(request, Perms.ADMIN_TOOLS ) ) );
                  if ( !has_rights )
                  {
                        request.getRequestDispatcher( "/frw.do?fw=norights" ).
                              forward( request, response );
                        return;
                  }


                  bean.put( PNAME_USER, user );
                  bean.put( PNAME_ACTION, action );
            }
            else if ( PV_ACTION_NEW.equals( action ) || PV_ACTION_REGISTER.equals( action ) )
            {
                  User user = new User();
                  bean.put( PNAME_USER, user );
            }
            else
            {
                  beans.remove( key );
                  response.sendError( HttpServletResponse.SC_NOT_FOUND );
                  return;
            }
      }

      protected void save(
            ServletContext application,
            HttpServletRequest request,
            HttpServletResponse response )
            throws IOException, ServletException
      {
            PersistenceToken token = PersistenceManager.
                  tokenLookup( this.getServletContext() );
            UserDB udb = UserDB.getManager( token );

            Hashtable bean = ( Hashtable ) request.getAttribute( PNAME_BEAN );
            Hashtable beans = ( Hashtable ) request.getSession().getAttribute( PNAME_BEANS );
            User item = ( User ) bean.get( PNAME_USER );
            String action = ( String ) bean.get( PNAME_ACTION );
            String[] errors = null;

            try
            {
                  if ( PV_ACTION_DELETE.equals( action ) )
                  {
                        UserDB.getManager( token ).delete( item.getId() );
                  }
                  else if ( PV_ACTION_NEW.equals( action ) )
                  {
                        udb.insert( item );
                  }
                  else if ( PV_ACTION_REGISTER.equals( action ) )
                  {
                        item.setStandby( true );
                        udb.insert( item );
                  }
                  else
                  {
                        udb.update( item );
                  }
            }
            catch ( SQLException e )
            {
                  errors = new String[]{e.getMessage()};
                  e.printStackTrace();
            }

            if ( errors == null )
            {
                  beans.remove( bean.get( PNAME_KEY ) );

                  if ( bean.get( "REGISTERING" ) != null )
                  {
                        Translator_DB translator_db = ( Translator_DB ) application.
                              getAttribute( TranslatorConstants.DB_TRANSLATOR );
                        Module_DB module = translator_db.getModule( "reg_msgs" );

                        StringBuffer sb = new StringBuffer();
                        sb.append( module.getMessage( item.getWorkingLanguage(), "user_prefix" ) ).append(" ");
                        sb.append( item.getFirstNames() ).append( " " ).append( item.getLastName() );
                        sb.append( ",<br><br>" );
                        sb.append( module.getMessage( item.getWorkingLanguage(), "thx_line" ) );
                        sb.append( "<br><br>" );
                        sb.append( module.getMessage( item.getWorkingLanguage(), "confirm_line" ) );
                        sb.append( "<br><br><br>" );
                        sb.append( module.getMessage( item.getWorkingLanguage(), "account_line" ) );
                        sb.append( "<br><br><br>" );
                        if ( item.getFirstNames() != null )
                        {
                              sb.append( module.getMessage( item.getWorkingLanguage(), "first_name_line" ) );
                              sb.append( ":" ).append( item.getFirstNames() ).append( "<br>" );
                        }
                        if ( item.getLastName() != null )
                        {
                              sb.append( module.getMessage( item.getWorkingLanguage(), "last_name_line" ) );
                              sb.append( ":" ).append( item.getLastName() ).append( "<br>" );
                        }
                        sb.append( module.getMessage( item.getWorkingLanguage(), "email_line" ) );
                        sb.append( ":" ).append( item.getEmail() ).append( "<br>" );
                        if ( item.getOrganization() != null )
                        {
                              sb.append( module.getMessage( item.getWorkingLanguage(), "org_line" ) );
                              sb.append( ":" ).append( item.getOrganization() ).append( "<br>" );
                        }
                        if ( item.getCountry_iso3() != null )
                        {
                              try
                              {
                                    Country country = AIDALocationDB.getManager( token )
                                          .getCountryByISO3( item.getCountry_iso3() );
                                    if ( country != null )
                                    {
                                          sb.append( module.getMessage( item.getWorkingLanguage(), "country_line" ) );
                                          sb.append( ":" ).append( country.getName() ).append( "<br>" );
                                    }
                              }
                              catch ( Exception ex )
                              {
                              }
                        }
                        sb.append( module.getMessage( item.getWorkingLanguage(), "user_line" ) );
                        sb.append( ":" ).append( item.getLogin() ).append( "<br>" );
                        sb.append( module.getMessage( item.getWorkingLanguage(), "pass_line" ) );
                        sb.append( ":" ).append( item.getClear_password() ).append( "<br><br>" );
                        item.setClear_password( null );
                        //sb.append( module.getMessage( item.getWorkingLanguage(), "footer" ) );
                        LPDRelay.getManager( token ).sendMail(
                              module.getMessage( item.getWorkingLanguage(), "subject" ),
                              sb.toString(), item.getEmail() );

                        if ( "true".equals( Utils.getProperty( token, SysProp.REGISTER_AUTO_LOGIN ) ) )
                        {
                              request.getSession().setAttribute( UserConstants.LOGGED_USER, item );
                        }

                        request.getSession().setAttribute( "registered_user", item );
                        response.sendRedirect( request.getContextPath() + "/after_register_note.jsp" );
                        return;
                  }

                  response.sendRedirect( ( String ) bean.get( PNAME_REFERER ) );
                  return;
            }
            else
            {
                  request.setAttribute( PNAME_SCREEN, PV_SCR_ERROR );
                  request.setAttribute( PNAME_ERRORS, errors );
                  request.getRequestDispatcher( JSP_PAGE ).
                        forward( request, response );
                  return;
            }
      }

      public static final String PNAME_BEANS = "EDITING_USERS";
      public static final String PNAME_USER = "USER";
      public static final String JSP_PAGE = "/usr/editUser.jsp";
      public static final String PNAME_ERRORS = "errors";
      public static final String PV_ACTION_REGISTER = "register";
}
